﻿using Zhongjiu.Common;
using Zhongjiu.Extensions;
using Zhongjiu.Gateway.Extensions;
using Zhongjiu.AuthHelper;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Nacos.V2.DependencyInjection;

namespace Zhongjiu.Gateway
{
  public class Startup
  {
    /**
    *┌──────────────────────────────────────────────────────────────┐
    *│　描    述：模拟一个网关项目         
    *│　测    试：在网关swagger中查看具体的服务         
    *│　作    者：anson zhang                                             
    *└──────────────────────────────────────────────────────────────┘
    */
    public Startup(IConfiguration configuration, IWebHostEnvironment env)
    {
      //Appsettings.Init(configuration);
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {

      services.AddAuthentication_JWTSetup();

      services.AddAuthentication()
         .AddScheme<AuthenticationSchemeOptions, CustomAuthenticationHandler>(Permissions.GWName, _ => { });

      services.AddNacosSetup();
      //services.AddNacosV2Config(Appsettings.Configuration, null, "nacosConfig");
      //services.AddNacosV2Naming(Appsettings.Configuration, null, "nacos");
      //services.AddHostedService<ApiGateway.Helper.OcelotConfigurationTask>();

      services.AddCustomSwaggerSetup();

      services.AddControllers();

      services.AddHttpContextSetup();

      services.AddCorsSetup();

      services.AddCustomOcelotSetup();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime)
    {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }

      app.UseRouting();

      app.UseAuthentication();
      app.UseAuthorization();

      app.UseCustomSwaggerMidd();

      app.UseCors(Appsettings.app(new string[] { "Startup", "Cors", "PolicyName" }));

      app.UseEndpoints(endpoints =>
      {
        //endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapControllers();
      });

      //app.UseMiddleware<CustomJwtTokenAuthMiddleware>();
      app.UseConsulRegistMiddle(lifetime);
      app.UseCustomOcelotMidd().Wait();
    }
  }
}
